//
//  CZPageView.m
//  ForChangZhou
//
//  Created by 蔺百好 on 2021/1/13.
//  Copyright © 2021 KMasker. All rights reserved.
//

#import "CZPageView.h"
@interface CZPageView () <UIScrollViewDelegate>

@property (nonatomic ,strong) UIScrollView *itemScrollView;

@property (nonatomic ,strong) UIView       *lineView;

@property (nonatomic ,strong) CZPageItem       *remarkItem;

@property (nonatomic ,strong) NSMutableArray  <CZPageItem *>     *itemBtnArray;


@property (nonatomic, assign) CGFloat      startOffsetX;

@property (nonatomic, assign) CGFloat      totalWidth;

@property (nonatomic, assign) BOOL      tapAct;
@property (nonatomic, assign) BOOL      skipScrollAnimation;



@end

@implementation CZPageView

- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        _current = 0;
        self.itemBtnArray = @[].mutableCopy;
        [self addSubview:self.itemScrollView];
        [self.itemScrollView addSubview:self.lineView];
    }
    return self;
}

- (void)setConfig:(CZPageConfig *)config {
    _config = config;
    
    self.lineView.backgroundColor = config.lineColor;
    self.lineView.layer.masksToBounds = YES;
    self.lineView.layer.cornerRadius = config.lineRadius;
}

- (void)setRelationScrollView:(UIScrollView *)relationScrollView {
    _relationScrollView = relationScrollView;
    _relationScrollView.delegate = self;
}

- (void)refreshSegmentTheme {
 
    
    for (CZPageItem * item in self.itemBtnArray) {
        [item refreshTheme];
    }
}

- (void)setItemArray:(NSArray<CZTopSegMentItemModel *> *)itemArray {
    _itemArray = itemArray;
    if (self.itemBtnArray.count != 0) {
        [self.itemBtnArray removeAllObjects];
        
        for (UIView * sub_view in self.itemScrollView.subviews) {
            if ([sub_view isKindOfClass:[CZPageItem class]]) {
                [sub_view removeFromSuperview];
            }
        }
    }
    [self setCurrent:0];
    [self createItem];
    [self countTotalWidth];
    self.itemScrollView.contentSize = CGSizeMake(self.totalWidth, 0);
}

- (void)createItem {
    CGFloat startX = self.config.leadingSpace;
    if (self.config.divideScreenWidth == YES) {
        startX = 0;
    }
    CGFloat space = self.config.itemSpace;
    CGFloat devideWidth = self.frame.size.width/self.itemArray.count;
    
    for (NSInteger i = 0; i < self.itemArray.count; i ++) {
        CZTopSegMentItemModel * model = [self.itemArray objectAtIndex:i];
        CZPageItem * item = [CZPageItem buttonWithType:UIButtonTypeCustom];
        item.itemModel = model;
        item.config = self.config;
        item.tag = i+100;
        item.chosen = i == self.current;
        if (self.config.divideScreenWidth == YES) {
            item.frame = CGRectMake(startX, 0, devideWidth, self.frame.size.height);
        }else {
            item.frame = CGRectMake(startX, 0, model.itemWidth, self.frame.size.height);
        }
        model.itemStartX = startX;
        [item addTarget:self action:@selector(pageDidSelectAct:) forControlEvents:UIControlEventTouchUpInside];
        [self.itemBtnArray addObject:item];
        
        if (self.config.divideScreenWidth == YES) {
            startX = startX+devideWidth;
        }else {
            startX = startX+model.itemWidth+space;
        }
        
        [self.itemScrollView addSubview:item];
        
        if (i == 0) {
            self.lineView.frame = CGRectMake(item.center.x-self.config.lineSize.width/2.0, self.frame.size.height-self.config.lineSize.height-1, self.config.lineSize.width, self.config.lineSize.height);
            
            self.remarkItem = item;
        }
    }
    
    [self.itemScrollView bringSubviewToFront:self.lineView];
}

- (void)setCurrent:(NSInteger)current {
    _current = current;
    
    if (self.itemBtnArray.count==0)
    {
        return;
    }
    CZPageItem * currentBtn = [self.itemBtnArray objectAtIndex:current];
    if (currentBtn == self.remarkItem) {
        return;
    }
    
    self.skipScrollAnimation = YES;
    currentBtn.chosen = YES;
    self.remarkItem.chosen = NO;
    self.remarkItem = currentBtn;
    if (self.tapAct == YES) {
        [UIView animateWithDuration:0.15 animations:^{
            self.lineView.center = CGPointMake(currentBtn.center.x, (self.frame.size.height-self.config.lineSize.height-1)+self.config.lineSize.height/2.0);
        }];
    }else {
        
        self.lineView.center = CGPointMake(currentBtn.center.x, (self.frame.size.height-self.config.lineSize.height-1)+self.config.lineSize.height/2.0);
    }
    [self.relationScrollView setContentOffset:CGPointMake(current*self.relationScrollView.frame.size.width, 0) animated:NO];
    
    [self changeToItem:currentBtn];
    
    self.tapAct = NO;
    
    
}

- (void)pageDidSelectAct:(CZPageItem *)sender {
    if (sender == self.remarkItem) {
        return;
    }
    self.tapAct = YES;
    self.current = sender.tag-100;
    
    if ([self.delegate respondsToSelector:@selector(pageViewSelectdIndex:withModel:withPageView:)]) {
        [self.delegate pageViewSelectdIndex:sender.tag-100 withModel:sender.itemModel withPageView:self];
    }
}

- (void)changeToItem:(CZPageItem *)item {
  
    if (self.totalWidth > self.itemScrollView.frame.size.width) {
        CGFloat posX = 0;

        if (item.center.x > self.itemScrollView.frame.size.width/2.0) {
            posX = item.center.x-self.itemScrollView.frame.size.width/2.0;
            if (self.totalWidth-item.center.x < self.itemScrollView.frame.size.width/2.0) {
                posX = self.totalWidth-self.itemScrollView.frame.size.width;
            }
        }
        [self.itemScrollView setContentOffset:CGPointMake(posX, 0) animated:YES];
    }
}


// MARK: UIScrollViewDelegate
#pragma mark UIScrollViewDelegate
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
{
    if (scrollView == self.itemScrollView) {
        return;
    }
    self.startOffsetX = scrollView.contentOffset.x;
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    if (scrollView == self.itemScrollView) {
        return;
    }
    if (scrollView.contentOffset.x < 0 || scrollView.contentOffset.x > (self.relationScrollView.contentSize.width-self.relationScrollView.frame.size.width)) {
        return;
    }
    //目标Index
    NSInteger targetIndex = 0;
    CGFloat currentOffsetX = scrollView.contentOffset.x;
    
    //滚动的百分比
    CGFloat progress = currentOffsetX-self.startOffsetX;
    
    //左滑
    if (currentOffsetX > self.startOffsetX)
    {
        if (self.current < self.itemArray.count-1) {
            targetIndex = self.current + 1;
        }
    }
    //右滑
    else
    {
        if (self.current != 0) {
            targetIndex = self.current - 1;
        }
    }
    
    if (self.tapAct == NO) {
        [self pageViewProgress:progress targetIndex:targetIndex];
    }

    self.startOffsetX = currentOffsetX;
}


- (void)pageViewProgress:(CGFloat)progress targetIndex:(NSInteger)targetIndex
{
    //初始
    CZPageItem * sourceItem = [self.itemBtnArray objectAtIndex:self.current];
    //目标
    CZPageItem * targetItem = [self.itemBtnArray objectAtIndex:targetIndex];
    //两者间距
    CGFloat spacing = fabs(targetItem.center.x-sourceItem.center.x);
    CGFloat lineProcess =  (spacing*progress) / self.relationScrollView.frame.size.width;
    if (sourceItem != targetItem) {
        if (self.skipScrollAnimation == YES) {
            self.skipScrollAnimation = NO;
            return;
        }
        CGPoint point = self.lineView.center;
        point.x += lineProcess;
        self.lineView.center = point;
    }else {
        [UIView animateWithDuration:0.15 animations:^{
            self.lineView.center = CGPointMake(sourceItem.center.x, (self.frame.size.height-self.config.lineSize.height-1)+self.config.lineSize.height/2.0);
        }];
    }
}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
    if (scrollView == self.relationScrollView) {
        return;
    }
    NSInteger sourceIndex = scrollView.contentOffset.x/scrollView.frame.size.width;
    [self setCurrent:sourceIndex];
    
    CZTopSegMentItemModel * model = [self.itemArray objectAtIndex:sourceIndex];

    if ([self.delegate respondsToSelector:@selector(pageViewSelectdIndex:withModel:withPageView:)]) {
        [self.delegate pageViewSelectdIndex:sourceIndex withModel:model withPageView:self];
    }
}

- (UIScrollView *)itemScrollView {
    if (!_itemScrollView) {
        _itemScrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, self.frame.size.width, self.frame.size.height)];
        _itemScrollView.showsVerticalScrollIndicator = NO;
        _itemScrollView.showsHorizontalScrollIndicator = NO;
        _itemScrollView.scrollsToTop = NO;
    }
    return  _itemScrollView;
}

- (UIView *)lineView {
    if (!_lineView) {
        _lineView = [[UIView alloc] init];
        _lineView.layer.masksToBounds = YES;
    }
    return _lineView;
}


- (void)countTotalWidth {
    self.totalWidth = 0;
    if (self.config.divideScreenWidth == NO) {
        self.totalWidth = self.config.leadingSpace;
        
        for (CZTopSegMentItemModel * model in self.itemArray) {
            self.totalWidth = self.totalWidth+model.itemWidth+self.config.itemSpace;
        }
        self.totalWidth = self.totalWidth+self.config.tralingSpace;
    }else {
        self.totalWidth = self.itemScrollView.frame.size.width;
    }
}

- (void)refreshTitle:(NSString *)title withIndex:(NSInteger)index {
    CZTopSegMentItemModel * model = [self.itemArray objectAtIndex:index];
    model.itemName = title;

    CGFloat devideWidth = self.frame.size.width/self.itemArray.count;
    CGFloat startX = model.itemStartX;
    for (NSInteger i = index; i < self.itemArray.count; i ++) {
        CZTopSegMentItemModel * model = [self.itemArray objectAtIndex:i];
        CZPageItem * item = [self.itemBtnArray objectAtIndex:i];
        item.itemModel = model;
        if (self.config.divideScreenWidth == YES) {
            item.frame = CGRectMake(startX, 0, devideWidth, self.frame.size.height);
        }else {
            item.frame = CGRectMake(startX, 0, model.itemWidth, self.frame.size.height);
        }
        model.itemStartX = startX;
        if (self.config.divideScreenWidth == YES) {
            startX = startX+devideWidth;
        }else {
            startX = startX+model.itemWidth+self.config.itemSpace;
        }
    }

    [self countTotalWidth];
    self.itemScrollView.contentSize = CGSizeMake(self.totalWidth, 0);
}

@end
